namespace ASPNET.StarterKit.IssueTracker.BusinessLogicLayer
{
    using System;
    using System.Collections;

    public class CategoryTree
    {
        private int _CatIndent = 1;
        private CategoryCollection _SortedCats;
        private CategoryCollection _UnSortedCats;

        public void BindSubCategories(int parentId)
        {
            IEnumerator _Vb_t_ref_0 = null;
            try
            {
                _Vb_t_ref_0 = this.GetChildCategories(parentId).GetEnumerator();
                while (_Vb_t_ref_0.MoveNext())
                {
                    Category childCat = (Category)_Vb_t_ref_0.Current;
                    this._SortedCats.Add(new Category(this.DisplayIndent() + childCat.Name, childCat.Id));
                    this._CatIndent++;
                    this.BindSubCategories(childCat.Id);
                    this._CatIndent--;
                }
            }
            finally
            {
                if (_Vb_t_ref_0 is IDisposable)
                {
                    ((IDisposable)_Vb_t_ref_0).Dispose();
                }
            }
        }

        public string DisplayIndent()
        {
            return (new string('-', this._CatIndent) + " ");
        }

        public CategoryCollection GetCategoryTreeByProjectId(int projectId)
        {
            this._SortedCats = new CategoryCollection();
            this._UnSortedCats = Category.GetCategoryByProjectId(projectId);
            foreach (Category parentCat in this.GetTopLevelCategories())
            {
                this._SortedCats.Add(parentCat);
                this.BindSubCategories(parentCat.Id);
            }
            return this._SortedCats;
        }

        public CategoryCollection GetChildCategories(int parentId)
        {
            CategoryCollection colCats = new CategoryCollection();
            foreach (Category cat in this._UnSortedCats)
            {
                if (cat.ParentCategoryId == parentId)
                {
                    colCats.Add(cat);
                }
            }
            return colCats;
        }

        public CategoryCollection GetTopLevelCategories()
        {
            CategoryCollection colCats = new CategoryCollection();
            foreach (Category cat in this._UnSortedCats)
            {
                if (cat.ParentCategoryId == 0)
                {
                    colCats.Add(cat);
                }
            }
            return colCats;
        }
    }
}

